# -*- coding: utf-8 -*-
"""
@project: SYL-Index-Sys

@desc: 数据管理部分：数据管理界面只对学校管理员可见
"""


from flask import Blueprint, request
from flask_login import login_required, current_user
import os
import json
from models import Message, Point, File, Record, User, Subject
from app import db
import time
from globals import SUJECT_INDEX_COUNT as subject_index_count
from upload import get_dateformat

# 数据管理
data_manage = Blueprint('data_manage', __name__)


@data_manage.route("/data-manage/university-index")
@login_required
def load_university_index():
    role_id = current_user.role_id
    if role_id != 1:
        return json.dumps({"status_code":403, "info":"您没有权限浏览该项目"}, ensure_ascii=False)
    # 加载所有的大学数据的指标
    points = Point.query.filter_by(point_type='D') # 加载所有的大学监测点
    data = []
    for point in points:
        data_json = {}
        data_json['id'] = point.id #id
        data_json['project'] = point.project
        data_json['factor'] = point.factor
        data_json['point'] = point.point
        data_json['content'] = point.content
        data_json['explain'] = point.explain
        # 是否已经上传，没有上传的话，无法查看，无法撤回
        data_json['has_upload'] = True if File.query.filter_by(point=point.id, status="已上传").first() else False
        records = Record.query.filter_by(point_id=point.id).limit(6).all() # 限制显示6条
        data_json['record'] = []
        for record in records:
            user = User.query.filter_by(id = record.user_id).first()
            upload_time = record.upload_time # 历史事件
            op_type = record.op_type # 操作行为
            record_str = '  '.join([user.name, str(upload_time), op_type])
            data_json['record'].append(record_str)
        data.append(data_json)
    return json.dumps({"data":data}, ensure_ascii="False")


@data_manage.route("/data-manage/subject-list")
@login_required
def load_subject_list():
    """
    加载学科列表
    :return:
    """
    role_id = current_user.role_id
    if role_id != 1:
        return json.dumps({"status_code":403, "info":"您没有权限浏览该项目"}, ensure_ascii=False)
    subjects = Subject.query.all()
    data = []
    for index, subject in enumerate(subjects):
        item = {}
        item['id'] = subject.id
        item['code'] = subject.code # 学科代码
        item['subject'] = subject.name # 学科的编号
        sql = 'SELECT count(1) FROM files WHERE file_type="%s"' % subject.name
        item['count'] = db.session.execute(sql).first()[0]
        item['total'] = subject_index_count
        # item['process'] = '%.2f%%' % (count / subject_index_count * 100)
        data.append(item)
    return json.dumps({"data" : data}, ensure_ascii=False)


@data_manage.route("/data-manage/subject-index", methods=['GET'])
@login_required
def load_subject_index():
    """
    加载数据管理部分：学科的指标
    :return:
    """
    role_id = current_user.role_id
    if role_id != 1:
        return json.dumps({"status_code":403, "info":"您没有权限浏览该项目"}, ensure_ascii=False)

    # request_data = json.loads(request.get_data().decode('utf-8'))
    subject = request.args.get('subject')

    points = Point.query.filter_by(point_type='X').all() # 查询所有的学科指标
    data = []
    for point in points:
        data_json = {}
        data_json['id'] = point.id
        data_json['project'] = point.project
        data_json['factor'] = point.factor
        data_json['point'] = point.point
        data_json['content'] = point.content
        data_json['explain'] = point.explain
        has_upload = False
        file = File.query.filter_by(point=point.id, status='已上传', file_type=subject).first()
        if file and os.path.exists(file.path):
            has_upload = True
        data_json['has_upload'] = has_upload
        # 最多显示6条
        records = Record.query.filter_by(point_id = point.id, record_type=subject).limit(6).all()
        data_json['record'] = []
        for record in records:
            user = User.query.filter_by(id=record.user_id).first()
            user_name = user.name if user else ''
            upload_time = record.upload_time
            op_type = record.op_type
            record_str = '  '.join([user_name, str(upload_time), op_type])
            data_json['record'].append(record_str)
        data.append(data_json)
    return json.dumps({"data":data}, ensure_ascii=False)

@data_manage.route("/data-manage/messages")
@login_required
def load_messages():
    """
    每个用户只加载自己的消息，管理员加载所有的消息
    :return:
    """
    if current_user.role_id == 1: # 如果是系统管理员
        messages = Message.query.all()
    else:
        messages = Message.query.filter_by(user_id = current_user.id).all()
    data = []
    for message in messages:
        item = {}
        item['username'] = User.query.filter_by(id=message.user_id).first().name
        item['point'] = message.point
        item['time'] = str(message.withdraw_time)
        item['reason'] = message.reason
        data.append(item)
    return json.dumps({'data':data}, ensure_ascii=False)

# 退回，需要改变文件的状态，并且增加一条消息到数据表
@data_manage.route('/data-manage/withdraw/<point_id>', methods=['POST'])
@login_required
def withdraw(point_id):
    # File文件里面, 一定会查到。
    # 更新当前文件的状态
    role_id = current_user.role_id
    if role_id != 1:
        return json.dumps({"status_code":403, "info":"您没有权限浏览该项目"}, ensure_ascii=False)
    request_data = json.loads(request.get_data().decode('utf8'))
    subject = request_data['subject'] # 学科
    reason = request_data['reason'] # 退回的原因
    print(subject, reason)
    try:
        # 修改状态为已撤回
        # File.query.filter_by(point=point_id, file_type=subject).update({'status': '已撤回'})
        # db.session.commit()
        file = File.query.filter_by(point=point_id, file_type=subject).first()
        upload_time = get_dateformat()
        # 更新记录表
        record = Record(point_id=point_id, # point_id
                        file_name=file.name, # 文件名
                        record_type=subject, # 学科名
                        user_id=file.user_id, # 文件隶属的用户id
                        upload_time=upload_time,
                        op_type="被撤回")
        db.session.add(record) # 提交被撤回的记录
        db.session.commit()
        # 更新消息表
        message = Message(point=point_id,
                          withdraw_time=upload_time,
                          reason=reason,
                          user_id=file.user_id)
        db.session.add(message)
        db.session.commit()

        if os.path.exists(file.path): # 删除文件
            os.remove(file.path)
        File.query.filter_by(point=point_id, file_type=subject).delete() # 删除这条记录
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
    # 发送一条json过去，立刻更新当前point_id的状态
    return json.dumps({'status_code':200, 'id':point_id, 'state':'已撤回'}, ensure_ascii=False)

@data_manage.route('/data-manage/withdraw-whole-subject', methods=['POST'])
@login_required
def withdraw_whole_subject():
    role_id = current_user.role_id
    if role_id != 1:
        return json.dumps({"status_code":403, "info":"您没有权限浏览该项目"}, ensure_ascii=False)
    request_data = json.loads(request.get_data().decode('utf8'))
    subject = request_data['subject'] # 学科
    reason = request_data['reason'] # 退回的原因
    files = File.query.filter_by(file_type=subject).all()
    for file in files:
        try:
            upload_time = get_dateformat()
            # 更新记录表
            record = Record(point_id=file.point,  # point_id
                            file_name=file.name,  # 文件名
                            record_type=subject,  # 学科名
                            user_id=file.user_id,  # 文件隶属的用户id
                            upload_time=upload_time,
                            op_type="被撤回")
            db.session.add(record)  # 提交被撤回的记录
            db.session.commit()
            # 更新消息表
            message = Message(point=file.point,
                              withdraw_time=upload_time,
                              reason=reason,
                              user_id=file.user_id)
            db.session.add(message)
            db.session.commit()

            if os.path.exists(file.path):  # 删除文件
                os.remove(file.path)
            File.query.filter_by(point=file.point, file_type=subject).delete()  # 删除这条记录
            db.session.commit()
        except Exception as e:
            print(e)
            db.session.rollback()
    return json.dumps({"status_code":200, "info":"%s的数据已经被全部撤回" % subject})

@data_manage.route('/data-manage/withdraw-whole-university', methods=['POST'])
@login_required
def withdraw_whole_university():
    role_id = current_user.role_id
    if role_id != 1:
        return json.dumps({"status_code":403, "info":"您没有权限浏览该项目"}, ensure_ascii=False)
    request_data = json.loads(request.get_data().decode('utf8'))
    subject = request_data['subject']  # subject为大学
    reason = request_data['reason']  # 退回的原因
    files = File.query.filter_by(file_type=subject).all()
    for file in files:
        try:
            upload_time = get_dateformat()
            # 更新记录表
            record = Record(point_id=file.point,  # point_id
                            file_name=file.name,  # 文件名
                            record_type=subject,  # 学科名
                            user_id=file.user_id,  # 文件隶属的用户id
                            upload_time=upload_time,
                            op_type="被撤回")
            db.session.add(record)  # 提交被撤回的记录
            db.session.commit()
            # 更新消息表
            message = Message(point=file.point,
                              withdraw_time=upload_time,
                              reason=reason,
                              user_id=file.user_id)
            db.session.add(message)
            db.session.commit()

            if os.path.exists(file.path):  # 删除文件
                os.remove(file.path)
            File.query.filter_by(point=file.point, file_type=subject).delete()  # 删除这条记录
            db.session.commit()
        except Exception as e:
            print(e)
            db.session.rollback()
    return json.dumps({"status_code": 200, "info": "%s的数据已经被全部撤回" % subject}, ensure_ascii=False)

